//
//  ViewController.m
//  shayu
//
//  Created by liangang on 2017/9/12.
//  Copyright © 2017年 liangang. All rights reserved.
//

#import "detailViewController.h"
//#import "testApi.h"
#import <Webkit/Webkit.h>
#import "Masonry.h"
#import "MJRefresh.h"
#define KIsiPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

@interface detailViewController ()<WKNavigationDelegate,WKUIDelegate>
{
    WKWebView *webView ;
    UIProgressView *progressView;
    BOOL loadSuccess;
}
@end

@implementation detailViewController
-(void)internetCheck
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [ manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                //未知网络
                NSLog(@"未知网络");
                if (!loadSuccess) {
                    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
                }
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                //无法联网
                NSLog(@"无法联网");
                
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                //手机自带网络
                NSLog(@"当前使用的是2g/3g/4g网络");
                if (!loadSuccess) {
                    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
                }
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                //WIFI
                NSLog(@"当前在WIFI网络下");
                if (!loadSuccess) {
                    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
                }
            }
                
        }
    }];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    self.view.backgroundColor = [UIColor colorWithRed:51/255.0f green:51/255.0f blue:51/255.0f alpha:1];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    
    
    
    WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
    
    Configuration.allowsInlineMediaPlayback = YES;
    
    Configuration.selectionGranularity = YES;
    Configuration.allowsInlineMediaPlayback = YES;
    Configuration.mediaPlaybackRequiresUserAction = false;
    
    Configuration.processPool = [[WKProcessPool alloc] init];
    //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
    WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
    // 添加消息处理，注意：self指代的对象需要遵守WKScriptMessageHandler协议，结束时需要移除
    //    [UserContentController addScriptMessageHandler:self name:@"Native"];
    // 是否支持记忆读取
    Configuration.suppressesIncrementalRendering = YES;
    // 允许用户更改网页的设置
    Configuration.userContentController = UserContentController;
    webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:config];
    webView.navigationDelegate = self;
    webView.UIDelegate   = self;
    //    [webView setmask]
    webView.clipsToBounds= YES;
    self.automaticallyAdjustsScrollViewInsets   = NO;
    [webView setUserInteractionEnabled:YES];
    [self.view addSubview:webView];
    NSInteger stateHeight = 0;
    NSInteger bottomHeight = 0;
    NSInteger progressY =0;
    
    if (self.navigationController) {
        if (KIsiPhoneX) {
            stateHeight = 44;
            bottomHeight = 34;
            progressY = 64+24;
            
        }
        else
        {
            stateHeight =64;
            progressY = 64;
        }
    }
    else
    {
        if (KIsiPhoneX) {
            stateHeight = 44;
            bottomHeight = 34;
            progressY =44;
        }
        else
        {
            stateHeight = 20;
            progressY = 20;
        }
    }
    //
    
    //    if (self.navigationController) {
    //        if (KIsiPhoneX) {
    ////            progressY = 44+;
    //        }
    //    }
    
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(webView.superview);
        make.top.equalTo(webView.superview).offset(stateHeight);
        make.bottom.equalTo(webView.superview).offset(-bottomHeight);
    }];
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    progressView = [UIProgressView new];
    webView.clipsToBounds = YES;
    [self.view addSubview:progressView];
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        
        make.height.mas_equalTo(2);
        make.top.equalTo(self.view).offset(progressY);
        //        make.bottom.equalTo(webView.mas_top);
    }];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:0 target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"刷新" style:0 target:self action:@selector(reFresh)];
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"刷新" style:0 target:self action:@selector(reload)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
    
    
    
    //    testApi *api = [[testApi alloc]init];
    //    [api     startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
    //        NSString * a =request.responseJSONObject[@"limit"] ;
    //        if([a isEqualToString:@"YES"])
    //        {
    //
    //        }
    //        else
    //        {
    //            NSArray *array = [NSArray array];
    //            NSLog(@"%@",array[1]);
    //        }
    //    } failure:^(__kindof YTKBaseRequest *request) {
    //
    //    }];
    //
    
    
    //    UIButton *button = [UIButton new ];
    //    [self.view addSubview:button ];
    //    NSInteger bottom = 0;
    //    if (KIsiPhoneX)
    //    {
    //        bottom = 50+34;
    //    }
    //    else
    //    {
    //        bottom = 50;
    //    }
    //    [button mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.bottom.equalTo(button.superview).offset(-bottom);
    //        make.right.equalTo(button.superview).offset(-20);
    //        make.width.height.mas_equalTo(40);
    //    }];
    //    [button setImage:[UIImage imageNamed:@"backIcon"] forState:UIControlStateNormal];
    //    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self internetCheck];
    webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [webView reload];
    }];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
-(void)reFresh
{
    [webView reload];
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"start");
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    loadSuccess = YES;
    NSLog(@" didCommit");
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    loadSuccess = YES;
    NSLog(@" didFinish");
    [webView.scrollView.mj_header endRefreshing ];
    
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
}
-(void)reload
{
    [webView reload];
}
-(void)back
{
    if ([webView canGoBack]) {
        [webView goBack];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark ================ WKUIDelegate ================

// 获取js 里面的提示
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

// js 信息的交流
-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

// 交互。可输入的文本。
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
}

//KVO监听进度条
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//
//    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == webView) {
//        [self.progressView setAlpha:1.0f];
//        BOOL animated = webView.estimatedProgress > self.progressView.progress;
//        [self.progressView setProgress:webView.estimatedProgress animated:animated];
//
//        // Once complete, fade out UIProgressView
//        if(webView.estimatedProgress >= 1.0f) {
//            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
//                [self.progressView setAlpha:0.0f];
//            } completion:^(BOOL finished) {
//                [self.progressView setProgress:0.0f animated:NO];
//            }];
//        }
//    }
//    else {
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
//}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        if (object == webView) {
            NSLog(@"%.2f",webView.estimatedProgress);
            [progressView setAlpha:1.0f];
            [progressView setProgress:webView.estimatedProgress animated:YES];
            
            //            [self.progressView setAlpha:1.0f];
            //            [self.progressView setProgress:self.currentSubView.webView.estimatedProgress animated:YES];
            //
            if(webView.estimatedProgress >= 1.0f) {
                
                [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [progressView setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [progressView setProgress:0.0f animated:NO];
                }];
                //
            }
        }
        
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
        
    }
    else if ([keyPath isEqualToString:@"title"])
    {
        if (object == webView) {
            self.title = webView.title;
            
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
            
        }
    }
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    
    
    //如果是跳转一个新页面
    NSString *strRequest = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",strRequest);
    if ([strRequest containsString:@"OpenScan"]) {
        [[webMethod sharedInstance] openScane];
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else
        
        decisionHandler(WKNavigationActionPolicyAllow);
    //    NSLog(@" allHTTPHeaderFields  :   %@", navigationAction.request.allHTTPHeaderFields);
    //    if ([strRequest containsString: @"/Mobile/User/online_pay"]) {
    //
    //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest  ]];
    //        decisionHandler(WKNavigationActionPolicyCancel);
    //    }
    //    if([strRequest containsString:@"mqqwpa"])
    //    {
    //        [[UIApplication  sharedApplication ]  openURL :[NSURL URLWithString:strRequest]];
    //
    //
    //        decisionHandler(WKNavigationActionPolicyCancel);
    //    }
    //    else if ([strRequest containsString:@"fir"]||[strRequest containsString:@"qq"]||[strRequest containsString:@"pgyer"]||[strRequest containsString:@"guanzhu"]||[strRequest containsString:@"9dun"]||[strRequest containsString:@"185sy"]||[strRequest containsString:@"dafuvip"])
    //    {
    //        [[UIApplication  sharedApplication ]  openURL :[NSURL URLWithString:strRequest]];
    //        decisionHandler(WKNavigationActionPolicyCancel);
    //    }
    //    //    if (navigationAction.targetFrame == nil) {
    //    //        [webView loadRequest:navigationAction.request];
    //    //    }
    //    else
    //        decisionHandler(WKNavigationActionPolicyAllow);
}

- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration  request     %@",navigationAction.request);
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


